package com.molichuxing.gateway.api.aspect;

import java.time.LocalDateTime;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.molichuxing.framework.dto.RequestRootDto;
import com.molichuxing.framework.property.OperatorTypeEnum;
import com.molichuxing.framework.result.ResponseCodeEnum;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.gateway.bff.user.entity.response.UserVo;
import com.molichuxing.gateway.utils.contants.RequestAttrConst;
import com.molichuxing.gateway.utils.redis.TokenUtil;
import com.molichuxing.services.property.OrderSourceEnum;

/**
 * 登录过滤
 * 
 * @author zoumingyu
 * @date 2019年8月8日
 *
 */
@Aspect
@Order(1)
public class TokenAspect {
	private final static Logger logger = LoggerFactory.getLogger("[mobile-gateway登录过滤]");

	@Resource
	private TokenUtil tokenUtil;

	@Value("${wechat.appid}")
	private String appid;

	@Value("${wechat.appsecret}")
	private String appsecret;

	@Value("${base.url}")
	private String baseUrl;

	private List<String> excludeMapping;

	public void setExcludeMapping(List<String> excludeMapping) {
		this.excludeMapping = excludeMapping;
	}

	@Pointcut("execution(public * com.molichuxing.gateway.api.services.impl..*(..))")
	public void token() {
	}

	@Around("token()")
	public Object doBefore(ProceedingJoinPoint joinPoint) throws Throwable {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		HttpServletResponse response = attributes.getResponse();
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "*");
		response.setHeader("Access-Control-Allow-Headers",
				"Origin,Content-Type,Accept,channel,token,workertoken,bondtoken,X-Requested-With");
		response.setHeader("Access-Control-Allow-Credentials", "true");
		// 忽略OPTIONS预校验请求
		if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
			return joinPoint.proceed();
		}

		String uri = request.getRequestURI();
		// 放过不拦截接口
		for (String exclude : excludeMapping) {
			if (uri.equalsIgnoreCase(exclude)) {
				return joinPoint.proceed();
			}
		}

		String channel = request.getHeader("channel");
		String token = request.getHeader("token");
		String openId = request.getHeader("openId");
		Boolean flag = validateChannel(channel);
		if (!flag) {
			return errorChannel();
		}
		channel = channel.toUpperCase();
//		String userAgent = request.getHeader("user-agent").toLowerCase();

		if (OrderSourceEnum.JSAPI.equals(Enum.valueOf(OrderSourceEnum.class, channel))) {
			if (StringUtils.isBlank(openId)) {
//				String redirectUrl = baseUrl + "/moli/home"; // 回调地址
				String state = "moli"; // state参数
				String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
						+ "&redirect_uri=" + baseUrl + "&response_type=code&scope=snsapi_base&state=" + state
						+ "#wechat_redirect";
				return new ResponseResult<String>().error(ResponseCodeEnum.WECHAT_CODE.getCode(),
						ResponseCodeEnum.WECHAT_CODE.getMessage(), url);
			}
		}
		if (StringUtils.isBlank(token)) {
			return noLogin();
		}
		// 根据token从redis中获取操作人相关信息
		UserVo user = tokenUtil.getUser(token);
		if (user == null) {
			return noLogin();
		}
		// 查询用户信息，并存入request
		request.setAttribute(RequestAttrConst.USER_KEY, user);
		if (OrderSourceEnum.AIO.equals(Enum.valueOf(OrderSourceEnum.class, channel))) {
			tokenUtil.refreshTerminal(token);
		} else {
			tokenUtil.refresh(token);
		}

		Object[] objArray = joinPoint.getArgs();
		for (Object obj : objArray) {
			if (obj != null && obj instanceof RequestRootDto) {
				RequestRootDto dto = (RequestRootDto) obj;
				// 赋值操作人相关信息
				dto.setOperateId(user.getUserId()); // 操作人id
				dto.setOperateName(user.getRealName()); // 操作人姓名
				dto.setOperateDate(LocalDateTime.now()); // 操作时间
				dto.setOperatorType(OperatorTypeEnum.MEMBER); // 操作人类型-op
			}
		}

		return joinPoint.proceed();
	}

	private ResponseResult<String> noLogin() {
		return new ResponseResult<String>().error(ResponseCodeEnum.LOGIN_ERROR);
	}

	private ResponseResult<String> errorChannel() {
		return new ResponseResult<String>().error(ResponseCodeEnum.PARMS_ERROR_CHANNEL);
	}

	/**
	 * 验证渠道
	 * 
	 * @param channel
	 * @return
	 */
	private Boolean validateChannel(String channel) {
		if (StringUtils.isBlank(channel)) {
			return false;
		}
		channel = channel.toUpperCase();
		try {
			OrderSourceEnum valueOf = Enum.valueOf(OrderSourceEnum.class, channel);
			if (null == valueOf) {
				return false;
			}
		} catch (Exception e) {
			return false;
		}
		return true;
	}
}
